import { useSelector } from "react-redux";
import { Navigate, useLocation } from "react-router-dom";

// 定义一个私有路由组件
const PriviteRouter = ({ children, isAuth }) => {
  // 从redux中获取token
  const token = useSelector((state) => state.user.token);
  // 获取当前路由
  const location = useLocation();

  // 未登录 并且 该页面要求登录
  if (!token && isAuth) {
    // 跳转到登录页面，并将当前路由作为参数传递
    return (
      <Navigate to={`/login?from=${location.pathname}`} replace></Navigate>
    );
  }

  return children;
};

{/* <PriviteRouter></PriviteRouter>

const withPriviteRouter = (Comp, isAuth) => {
  const MiddleComp = (...props) => {
    const token = useSelector(state => state.user.token);

    if(!token && isAuth) {
      return <Navigate to={`/login?from=${location.pathname}`} replace></Navigate>
    }


    return <Comp {...props}></Comp>;
  };

  return MiddleComp;
};

withPriviteRouter(<div>哈哈</div>); */}

export default PriviteRouter;
